package com.tbit.uqbike.webmanager.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tbit.maintain.api.StockMachineApi;
import com.tbit.maintain.dto.StockMachineDTO;
import com.tbit.uqbike.annos.OperateLog;
import com.tbit.common.constant.MethodEnum;
import com.tbit.common.constant.ModuleEnum;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.Machine;
import com.tbit.uqbike.object.pojo.RecoveryLog;
import com.tbit.uqbike.object.pojo.dto.RecoveryDownloadDTO;
import com.tbit.uqbike.object.pojo.vo.StockMachineVO;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.object.view.JsonResult;
import com.tbit.common.entity.view.PageResult;
import com.tbit.common.entity.view.Result;
import com.tbit.uqbike.service.base.MachineService;
import com.tbit.uqbike.service.base.TokenService;
import com.tbit.uqbike.service.business.StockMachineService;
import com.tbit.uqbike.webmanager.util.Assert;
import com.tbit.uqbike.webmanager.util.csv.annotations.AsyncDownload;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 车辆出入库
 *
 * @author yee_
 * @version 1.0
 * @date 2023/2/10 10:21
 */
@Slf4j
@RestController
@RequestMapping("/stockMachine")
public class StockMachineController extends BaseController {

    @Resource
    private StockMachineService stockMachineService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private StockMachineApi stockMachineApi;
    @Autowired
    private MachineService machineService;

    /**
     * 车辆出入库
     *
     * @param request   .
     * @param accountId 。
     * @param userCode  。
     * @param page      。
     * @param size      。
     * @return .
     */
    @GetMapping("/queryPage")
    public Result<PageResult<StockMachineVO>> queryPage(HttpServletRequest request, Integer accountId, String userCode,
                                                        @RequestParam(defaultValue = "1") Integer page,
                                                        @RequestParam(defaultValue = "10") Integer size) {
        if (accountId == null) {
            LoginInfo loginInfo = getLogin(request);
            accountId = loginInfo.getAccountUserId();
        }
        return stockMachineService.pageList(accountId, userCode, Page.of(page, size));
    }

    /**
     * 计算车辆库存率
     *
     * @param request   。
     * @param accountId 运营区域id
     * @param userCode  设备码
     * @return 。
     */
    @GetMapping("/stockRate")
    public Result<Double> queryPage(HttpServletRequest request, Integer accountId, String userCode) {
        if (accountId == null) {
            LoginInfo loginInfo = getLogin(request);
            accountId = loginInfo.getAccountUserId();
        }
        return stockMachineService.selectMachineStockRate(accountId, userCode);
    }

    /**
     * 设备回收记录查询
     *
     * @param accountId .
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param state     状态 - 0-未入库  1-入库成功
     * @param page      页码
     * @param size      每页条数
     * @return .
     */
    @GetMapping("/recoveryList")
    public Result<PageResult<RecoveryLog>> recoveryList(@RequestParam List<Integer> accountId,   @RequestParam(required = false) String startTime,
                                                        @RequestParam(required = false)String endTime, @RequestParam(required = false) Integer state,
                                                        @RequestParam Integer dateState,
                                                        @RequestParam(required = false) String userCode,
                                                        @RequestParam(defaultValue = "1") Integer page,
                                                        @RequestParam(defaultValue = "10") Integer size) {

        return stockMachineService.recoveryList(userCode,dateState,accountId, startTime, endTime, state, Page.of(page, size));
    }
/*
    *//**
     *  根据仓库id查询入库车辆
     *//*
    @RequestMapping("/selectByWarehouseId")
    public JsonResult selectByWarehouseId( @RequestParam(name="warehouseId",required = false) List<Integer> warehouseId, Integer accountId) {
        List<StockMachineVO> stockMachineVOS = stockMachineService.selectByWarehouseIdS(warehouseId,accountId);
        return JsonResult.ok(stockMachineVOS);
    }*/


    /**
     * 批量出库
     *
     * @param userCodes 车辆编号
     * @param token     鉴权秘钥
     */
    @RequestMapping("/delBatch")
    @OperateLog(module = ModuleEnum.STOCKMACHINE, methods = MethodEnum.STOCKMACHINE_DEL)
    public Result delBatch(HttpServletRequest request,@RequestParam("userCodes") List<String> userCodes, String token,Integer accountId) {
        Assert.notNull(userCodes, "Machine.userCode.notNull");
        LoginInfo loginInfo = getLogin(request);
        Map<String, Object> map = stockMachineService.delBatch(userCodes, accountId, loginInfo);
        return Result.success(map);
    }


    /**
     * 批量更换仓库
     *
     * @param userCodes 车辆编号
     * @param token     鉴权秘钥
     */
    @RequestMapping("/updateBatch")
    @OperateLog(module = ModuleEnum.STOCKMACHINE, methods = MethodEnum.STOCKMACHINE_UPDATE)
    public JsonResult updateBatch(HttpServletRequest request,@RequestParam("userCodes") List<String> userCodes, String token,String warehouseName,String warehouseId) {
        Assert.notNull(userCodes, "Machine.userCode.notNull");
        LoginInfo loginInfo = getLogin(request);
        stockMachineService.updateBatch(userCodes, warehouseName,warehouseId,loginInfo);
        return JsonResult.ok();
    }

    @GetMapping("/export")
    @AsyncDownload(defaultFileName = "回收表")
    public Result<String> recoveryListDownloadCsv(RecoveryDownloadDTO downloadDTO) {
        String url = stockMachineService.recoveryListDownloadCsv(downloadDTO);
        return Result.success(url);
    }

    /**
     * 回收统计导出excel
     * @param downloadDTO 入参
     * @return excel
     */
    @GetMapping("/exportExcel")
    public Result<Object> recoveryListDownload(RecoveryDownloadDTO downloadDTO) {
        return stockMachineService.recoveryListDownload(downloadDTO);
    }

    /**
     *  根据仓库id查询入库车辆
     */
    @RequestMapping("/selectByWarehouseId")
    public Result selectByWarehouseId(HttpServletRequest request, String token,@RequestParam(name="warehouseId",required = false) List<Integer> warehouseId, String userCode, Integer accountId) {
        List<StockMachineVO> stockMachineVOS = stockMachineService.selectByWarehouseIdS(warehouseId,userCode,accountId);
        if (stockMachineVOS == null){
            stockMachineVOS = new ArrayList<>();
        }
        return Result.success(stockMachineVOS);
    }

    /**
     * @description:车辆入库
     * @author: mo.shanyong
     * @date: 2025/3/31 19:47
     * @param: stockMachineDTO
     * @return: com.tbit.common.entity.view.Result
     */
    @PostMapping("/add")
    @OperateLog(module = ModuleEnum.STOCKMACHINE, methods = MethodEnum.STOCKMACHINE_ADD)
    public Result add(@RequestBody StockMachineDTO stockMachineDTO,HttpServletRequest request){
        LoginInfo login = getLogin(request);
        stockMachineDTO.setAccountUserId(login.getAccountUserId());
        log.info("add-------------------->stockMachineDTO：{}", JSON.toJSONString(stockMachineDTO));
        Machine machine = machineService.getByUserCode(stockMachineDTO.getUserCodeList().get(0));
        if (Objects.isNull(machine)){
            throw new BaseException("车辆不存在");
        }
        stockMachineApi.add(stockMachineDTO);
        return Result.success();
    }

    /**
     * @description: 车辆出库
     * @author: mo.shanyong
     * @date: 2025/3/31 19:49
     * @param: stockMachineDTO
     * @return: com.tbit.common.entity.view.Result
     */
    @PostMapping("/del")
    @OperateLog(module = ModuleEnum.STOCKMACHINE, methods = MethodEnum.STOCKMACHINE_DEL)
    public Result del(@RequestBody StockMachineDTO stockMachineDTO,HttpServletRequest request){
        LoginInfo login = getLogin(request);
        stockMachineDTO.setAccountUserId(login.getAccountUserId());
        Machine machine = machineService.getByUserCode(stockMachineDTO.getUserCodeList().get(0));
        if (Objects.isNull(machine)){
            throw new BaseException("车辆不存在");
        }
        log.info("del-------------------->stockMachineDTO：{}", JSON.toJSONString(stockMachineDTO));
        stockMachineApi.del(stockMachineDTO);
        return Result.success();
    }
    /**
     * @description: 批量入库
     * @author: mo.shanyong
     * @date: 2025/3/31 19:50
     * @param: stockMachineDTO
     * @return: com.tbit.common.entity.view.Result
     */
    @PostMapping("/addBatch")
    @OperateLog(module = ModuleEnum.STOCKMACHINE, methods = MethodEnum.STOCKMACHINE_ADD)
    public Result addBatch(@RequestBody StockMachineDTO stockMachineDTO,HttpServletRequest request){
        log.info("del-------------------->stockMachineDTO：{}", JSON.toJSONString(stockMachineDTO));
        Map<String, Object> dataMap = stockMachineService.addBatch(stockMachineDTO, getLogin(request));
        return Result.success(dataMap);
    }


}
